import { Component, OnInit, Input, SimpleChanges, Output,EventEmitter } from '@angular/core';
import { EarlyWarningService } from "../../../../service/early-warning.service";
import { TurbEarlyWarn } from "../../../../entity/turb-early-warn.model";
import { EarlyWarningFarmData } from "../early-warning/early-warning-farm-data";
import { FarmService } from "../../../../service/farm.service";
import { Farm } from "../../../../entity/farm.model";

@Component({
  selector: 'app-early-warning',
  templateUrl: './early-warning.component.html',
  styleUrls: ['./early-warning.component.css']
})
export class EarlyWarningComponent implements OnInit {

  /**
   * 开始、结束时间
   */
  public endTime = new Date();
  public startTime: Date = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate(), this.endTime.getHours(), this.endTime.getMinutes() - 1, this.endTime.getSeconds())
  /**
   * 返回的条数
   * @param earlyWarningService 
   */
  public top: number = 50;
  //定时器
  public interval: any;
  /**
   * 所有预警集合(过滤后的)
   */
  public turbEarlyWarnDatas: TurbEarlyWarn[] = []
  /**
   * 所有预警集合
   */
  public allTurbEarlyWarnDatas: TurbEarlyWarn[] = [];

  /**
   * 报警信息按风场进行汇总
   * 
   * @type {AlarmCategoryFarmData[]}
   * @memberof AlarmLampComponent
   */
  public earlyWarningFarmDatas: EarlyWarningFarmData[] = [];
  /**
   * 所有风场集合
   * 
   * @type {AlarmCategoryFarmData[]}
   * @memberof AlarmLampComponent
   */
  public farms: Farm[] = [];
  /**
   * 定时器
   * 
   * @type {*}
   * @memberof AlarmLampComponent
   */
  public timeout:any;

  /**
   * 描述（模糊查询字段）
   * 
   * @type {string}
   * @memberof AlarmLampComponent
   */
  @Input() desc: string;

  /**
   * 状态（模糊查询字段）
   * 
   * @type {string}
   * @memberof AlarmLampComponent
   */
  @Input() stateName: string;

  /**
   * 预警数量
   * 
   * @memberof EarlyWarningComponent
   */
  @Output() 
  earlyWarningDataTotalChange = new EventEmitter<Number>();

  constructor(
    private earlyWarningService: EarlyWarningService,
    private farmService: FarmService,
  ) { }

  ngOnInit() {

    this.loadData(50, null, null);
    //清除定时器
    clearInterval(this.interval)
    //每隔一分钟发一次请求
    this.interval = setInterval(() => {
      this.endTime = new Date();
      this.startTime = new Date(this.endTime.getFullYear(), this.endTime.getMonth(), this.endTime.getDate(), this.endTime.getHours(), this.endTime.getMinutes() - 1, this.endTime.getSeconds())
      this.loadData(null, this.startTime, this.endTime)
    }, 60000)
  }

 ngOnChanges(changes: SimpleChanges) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      if(this.allTurbEarlyWarnDatas){
        this.turbEarlyWarnFilter()
      }
    }, 500);
  }

  /**
   * 加载数据
   */

  loadData(top, startTime, endTime) {
    Promise.all([
      this.farmService.getFarms(),
      this.earlyWarningService.getSysRTurbEarlyWarningList(top, startTime, endTime)])
      .then(res => {
        this.farms = res[0];
        // this.turbEarlyWarnDatas.unshift(...res[1]);
        // if (this.turbEarlyWarnDatas.length > 50) {
        //   this.turbEarlyWarnDatas = this.turbEarlyWarnDatas.slice(0, 50);          
        // }
        // this.turbEarlyWarnDatas.forEach(t=>{
        //     t.description = t.farmName+'-'+t.deviceName+'-'+t.tagName;
        //   })

        this.allTurbEarlyWarnDatas.unshift(...res[1]);
        if (this.allTurbEarlyWarnDatas.length > 50) {
          this.allTurbEarlyWarnDatas = this.allTurbEarlyWarnDatas.slice(0, 50);
        }
        this.allTurbEarlyWarnDatas.forEach(t => {
          t.description = t.farmName + '-' + t.deviceName + '-' + t.tagName;
        })

        this.turbEarlyWarnDatas = [...this.allTurbEarlyWarnDatas]
        //模糊查询
        this.turbEarlyWarnFilter();

        this.earlyWarningFarmDatas = [];
        this.farms.forEach((farm, i) => {
          let index = this.earlyWarningFarmDatas.findIndex(earlyFarm => farm.farmId == earlyFarm.farmId)
          if (index < 0) {
            //没有找到
            this.earlyWarningFarmDatas.push({
              farmId: farm.farmId,
              farmName: farm.farmName,
              turbEarlyWarns: [],
              isChecked: i == 0 ? true : false,
              earlyWarningNumber:0
            })
          }
        })

        this.allTurbEarlyWarnDatas.forEach((t, i) => {
          let index = this.earlyWarningFarmDatas.findIndex(o => o.farmId == t.farmId)
          if (index >= 0) {
            //找到了
            this.earlyWarningFarmDatas[index].turbEarlyWarns.unshift(t);
          } else {
            //没有找到
            this.earlyWarningFarmDatas.unshift({
              farmId: t.farmId,
              farmName: t.farmName,
              turbEarlyWarns: [t],
              isChecked: i == 0 ? true : false,
              earlyWarningNumber:0
            })
          }
        })
        this.EarlyWarningFarmDatasTotal()
        
        this.earlyWarningDataTotalChange.emit(this.turbEarlyWarnDatas.length);
        // console.log(this.earlyWarningFarmDatas)
      })
      .catch(error => {
        console.log("app-early-warning has error", error);
      })

  }

  /**
   * 过滤(模糊查询)
   */
  turbEarlyWarnFilter() {
    if (this.desc.length > 0) {
      // 有模糊查询字段，从this.allTurbEarlyWarnDatas里面进行过滤，赋值给this.turbEarlyWarnDatas
      this.turbEarlyWarnDatas = this.allTurbEarlyWarnDatas.filter(data =>{
        return data.description.includes(this.desc)
      })
    } else {
      if(this.allTurbEarlyWarnDatas){
        this.turbEarlyWarnDatas = [...this.allTurbEarlyWarnDatas]
      }
    }
    if (this.stateName.length > 0){
      //有模糊查询字段，从this.turbEarlyWarnDatas里面进行过滤，重新赋值给this.turbEarlyWarnDatas
      this.turbEarlyWarnDatas = this.turbEarlyWarnDatas.filter(data =>data.stateName == this.stateName)
    }
    //统计每个风场的条数
    this.EarlyWarningFarmDatasTotal()
  }
  //统计每个风场的条数
  EarlyWarningFarmDatasTotal(){
    this.earlyWarningFarmDatas.forEach(farmData =>{
      farmData.earlyWarningNumber =  farmData.turbEarlyWarns.length;
    })
  }




}



// WEBPACK FOOTER //
// ./src/app/module/navigation/alarm-lamp/early-warning/early-warning.component.ts